Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
The mqtt npm package is a client library for the MQTT protocol, which is a lightweight messaging protocol designed for small sensors and mobile devices. It allows you to connect to an MQTT broker, publish messages to topics, and subscribe to topics to receive messages.
Connect to an MQTT broker
This feature allows you to connect to an MQTT broker. The code sample demonstrates how to connect to a public MQTT broker (HiveMQ) and log a message upon successful connection.
const mqtt = require('mqtt');
const client = mqtt.connect('mqtt://broker.hivemq.com');
client.on('connect', () => {
console.log('Connected to broker');
});
Publish messages to a topic
This feature allows you to publish messages to a specific topic. The code sample shows how to publish a message 'Hello MQTT' to the topic 'test/topic' after connecting to the broker.
const mqtt = require('mqtt');
const client = mqtt.connect('mqtt://broker.hivemq.com');
client.on('connect', () => {
client.publish('test/topic', 'Hello MQTT');
console.log('Message published');
});
Subscribe to a topic
This feature allows you to subscribe to a specific topic and receive messages published to that topic. The code sample demonstrates subscribing to 'test/topic' and logging any received messages.
const mqtt = require('mqtt');
const client = mqtt.connect('mqtt://broker.hivemq.com');
client.on('connect', () => {
client.subscribe('test/topic', (err) => {
if (!err) {
console.log('Subscribed to topic');
}
});
});
client.on('message', (topic, message) => {
console.log(`Received message: ${message.toString()} on topic: ${topic}`);
});
mqttjs is another popular MQTT client library for Node.js. It offers similar functionalities to the mqtt package, including connecting to brokers, publishing, and subscribing to topics. It is known for its simplicity and ease of use.
aedes is a barebone MQTT broker that can be embedded in Node.js applications. While it serves as a broker rather than a client, it can be used in conjunction with mqtt to create a complete MQTT solution. It is lightweight and highly performant.
mosca is an MQTT broker that can be used with Node.js. It is designed to be fast and scalable, making it suitable for IoT applications. Like aedes, it can be used alongside mqtt to provide a full MQTT ecosystem.
MQTT.js is a client library for the MQTT protocol, written in JavaScript for node.js and the browser.
MQTT.js is an OPEN Open Source Project, see the Contributing section to find out what this means.
v2.0.0 removes support for node v0.8, v0.10 and v0.12, and it is 3x faster in sending
packets. It also removes all the deprecated functionality in v1.0.0,
mainly mqtt.createConnection
and mqtt.Server
. From v2.0.0,
subscriptions are restored upon reconnection if clean: true
.
v1.x.x is now in LTS, and it will keep being supported as long as
there are v0.8, v0.10 and v0.12 users.
v1.0.0 improves the overall architecture of the project, which is now split into three components: MQTT.js keeps the Client, mqtt-connection includes the barebone Connection code for server-side usage, and mqtt-packet includes the protocol parser and generator. The new Client improves performance by a 30% factor, embeds Websocket support (MOWS is now deprecated), and it has a better support for QoS 1 and 2. The previous API is still supported but deprecated, as such, it is not documented in this README.
As a breaking change, the encoding
option in the old client is
removed, and now everything is UTF-8 with the exception of the
password
in the CONNECT message and payload
in the PUBLISH message,
which are Buffer
.
Another breaking change is that MQTT.js now defaults to MQTT v3.1.1, so to support old brokers, please read the client options doc.
npm install mqtt --save
For the sake of simplicity, let's put the subscriber and the publisher in the same file:
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://test.mosquitto.org')
client.on('connect', function () {
client.subscribe('presence', function (err) {
if (!err) {
client.publish('presence', 'Hello mqtt')
}
})
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
output:
Hello mqtt
If you want to run your own MQTT broker, you can use Mosquitto or Mosca, and launch it. You can also use a test instance: test.mosquitto.org and test.mosca.io are both public.
If you do not want to install a separate broker, you can try using the mqtt-connection.
to use MQTT.js in the browser see the browserify section
If you want to use the new async-await functionality in JavaScript, or just prefer using Promises instead of callbacks, async-mqtt is a wrapper over MQTT.js which uses promises instead of callbacks when possible.
MQTT.js bundles a command to interact with a broker. In order to have it available on your path, you should install MQTT.js globally:
npm install mqtt -g
Then, on one terminal
mqtt sub -t 'hello' -h 'test.mosquitto.org' -v
On another
mqtt pub -t 'hello' -h 'test.mosquitto.org' -m 'from MQTT.js'
See mqtt help <command>
for the command help.
mqtt.connect()
mqtt.Client()
mqtt.Client#publish()
mqtt.Client#subscribe()
mqtt.Client#unsubscribe()
mqtt.Client#end()
mqtt.Client#removeOutgoingMessage()
mqtt.Client#reconnect()
mqtt.Client#handleMessage()
mqtt.Client#connected
mqtt.Client#reconnecting
mqtt.Client#getLastMessageId()
mqtt.Store()
mqtt.Store#put()
mqtt.Store#del()
mqtt.Store#createStream()
mqtt.Store#close()
Connects to the broker specified by the given url and options and returns a Client.
The URL can be on the following protocols: 'mqtt', 'mqtts', 'tcp',
'tls', 'ws', 'wss'. The URL can also be an object as returned by
URL.parse()
,
in that case the two objects are merged, i.e. you can pass a single
object with both the URL and the connect options.
You can also specify a servers
options with content: [{ host: 'localhost', port: 1883 }, ... ]
, in that case that array is iterated
at every connect.
For all MQTT-related options, see the Client constructor.
The Client
class wraps a client connection to an
MQTT broker over an arbitrary transport method (TCP, TLS,
WebSocket, ecc).
Client
automatically handles the following:
The arguments are:
streamBuilder
is a function that returns a subclass of the Stream
class that supports
the connect
event. Typically a net.Socket
.options
is the client connection options (see: the connect packet). Defaults:
wsOptions
: is the WebSocket connection options. Default is {}
.
It's specific for WebSockets. For possible options have a look at: https://github.com/websockets/ws/blob/master/doc/ws.md.keepalive
: 60
seconds, set to 0
to disablereschedulePings
: reschedule ping messages after sending packets (default true
)clientId
: 'mqttjs_' + Math.random().toString(16).substr(2, 8)
protocolId
: 'MQTT'
protocolVersion
: 4
clean
: true
, set to false to receive QoS 1 and 2 messages while
offlinereconnectPeriod
: 1000
milliseconds, interval between two
reconnectionsconnectTimeout
: 30 * 1000
milliseconds, time to wait before a
CONNACK is receivedusername
: the username required by your broker, if anypassword
: the password required by your broker, if anyincomingStore
: a Store for the incoming packetsoutgoingStore
: a Store for the outgoing packetsqueueQoSZero
: if connection is broken, queue outgoing QoS zero messages (default true
)will
: a message that will sent by the broker automatically when
the client disconnect badly. The format is:
topic
: the topic to publishpayload
: the message to publishqos
: the QoSretain
: the retain flagtransformWsUrl
: optional (url, options, client) => url
function
For ws/wss protocols only. Can be used to implement signing
urls which upon reconnect can have become expired.resubscribe
: if connection is broken and reconnects,
subscribed topics are automatically subscribed again (default true
)In case mqtts (mqtt over tls) is required, the options
object is
passed through to
tls.connect()
.
If you are using a self-signed certificate, pass the rejectUnauthorized: false
option.
Beware that you are exposing yourself to man in the middle attacks, so it is a configuration
that is not recommended for production environments.
If you are connecting to a broker that supports only MQTT 3.1 (not 3.1.1 compliant), you should pass these additional options:
{
protocolId: 'MQIsdp',
protocolVersion: 3
}
This is confirmed on RabbitMQ 3.2.4, and on Mosquitto < 1.3. Mosquitto version 1.3 and 1.4 works fine without those.
'connect'
function (connack) {}
Emitted on successful (re)connection (i.e. connack rc=0).
connack
received connack packet. When clean
connection option is false
and server has a previous session
for clientId
connection option, then connack.sessionPresent
flag is true
. When that is the case,
you may rely on stored session and prefer not to send subscribe commands for the client.'reconnect'
function () {}
Emitted when a reconnect starts.
'close'
function () {}
Emitted after a disconnection.
'offline'
function () {}
Emitted when the client goes offline.
'error'
function (error) {}
Emitted when the client cannot connect (i.e. connack rc != 0) or when a parsing error occurs.
'end'
function () {}
Emitted when mqtt.Client#end()
is called.
If a callback was passed to mqtt.Client#end()
, this event is emitted once the
callback returns.
'message'
function (topic, message, packet) {}
Emitted when the client receives a publish packet
topic
topic of the received packetmessage
payload of the received packetpacket
received packet, as defined in
mqtt-packet'packetsend'
function (packet) {}
Emitted when the client sends any packet. This includes .published() packets as well as packets used by MQTT for managing subscriptions and connections
packet
received packet, as defined in
mqtt-packet'packetreceive'
function (packet) {}
Emitted when the client receives any packet. This includes packets from subscribed topics as well as packets used by MQTT for managing subscriptions and connections
packet
received packet, as defined in
mqtt-packetPublish a message to a topic
topic
is the topic to publish to, String
message
is the message to publish, Buffer
or String
options
is the options to publish with, including:
qos
QoS level, Number
, default 0
retain
retain flag, Boolean
, default false
dup
mark as duplicate flag, Boolean
, default false
callback
- function (err)
, fired when the QoS handling completes,
or at the next tick if QoS 0. An error occurs if client is disconnecting.Subscribe to a topic or topics
topic
is a String
topic to subscribe to or an Array
of
topics to subscribe to. It can also be an object, it has as object
keys the topic name and as value the QoS, like {'test1': 0, 'test2': 1}
.
MQTT topic
wildcard characters are supported (+
- for single level and #
- for multi level)options
is the options to subscribe with, including:
qos
qos subscription level, default 0callback
- function (err, granted)
callback fired on suback where:
err
a subscription error or an error that occurs when client is disconnectinggranted
is an array of {topic, qos}
where:
topic
is a subscribed to topicqos
is the granted qos level on itUnsubscribe from a topic or topics
topic
is a String
topic or an array of topics to unsubscribe fromcallback
- function (err)
, fired on unsuback. An error occurs if client is disconnecting.Close the client, accepts the following options:
force
: passing it to true will close the client right away, without
waiting for the in-flight messages to be acked. This parameter is
optional.cb
: will be called when the client is closed. This parameter is
optional.Remove a message from the outgoingStore. The outgoing callback will be called with Error('Message removed') if the message is removed.
After this function is called, the messageId is released and becomes reusable.
mid
: The messageId of the message in the outgoingStore.Connect again using the same options as connect()
Handle messages with backpressure support, one at a time.
Override at will, but always call callback
, or the client
will hang.
Boolean : set to true
if the client is connected. false
otherwise.
Number : get last message id. This is for sent messages only.
Boolean : set to true
if the client is trying to reconnect to the server. false
otherwise.
In-memory implementation of the message store.
options
is the store options:
clean
: true
, clean inflight messages when close is called (default true
)Other implementations of mqtt.Store
:
Adds a packet to the store, a packet is
anything that has a messageId
property.
The callback is called when the packet has been stored.
Creates a stream with all the packets in the store.
Removes a packet from the store, a packet is
anything that has a messageId
property.
The callback is called when the packet has been removed.
Closes the Store.
The MQTT.js bundle is available through http://unpkg.com, specifically at https://unpkg.com/mqtt/dist/mqtt.min.js. See http://unpkg.com for the full documentation on version ranges.
Surport Weixin App. See Doc.
var mqtt = require('mqtt')
var client = mqtt.connect('wxs://test.mosquitto.org')
import { connect } from 'mqtt';
const client = connect('wxs://test.mosquitto.org');
In order to use MQTT.js as a browserify module you can either require it in your browserify bundles or build it as a stand alone module. The exported module is AMD/CommonJs compatible and it will add an object in the global space.
npm install -g browserify // install browserify
cd node_modules/mqtt
npm install . // install dev dependencies
browserify mqtt.js -s mqtt > browserMqtt.js // require mqtt in your client-side app
Just like browserify, export MQTT.js as library. The exported module would be var mqtt = xxx
and it will add an object in the global space. You could also export module in other formats (AMD/CommonJS/others) by setting output.libraryTarget in webpack configuration.
npm install -g webpack // install webpack
cd node_modules/mqtt
npm install . // install dev dependencies
webpack mqtt.js ./browserMqtt.js --output-library mqtt
you can then use mqtt.js in the browser with the same api than node's one.
<html>
<head>
<title>test Ws mqtt.js</title>
</head>
<body>
<script src="./browserMqtt.js"></script>
<script>
var client = mqtt.connect() // you add a ws:// url here
client.subscribe("mqtt/demo")
client.on("message", function (topic, payload) {
alert([topic, payload].join(": "))
client.end()
})
client.publish("mqtt/demo", "hello world!")
</script>
</body>
</html>
Your broker should accept websocket connection (see MQTT over Websockets to setup Mosca).
If you need to sign an url, for example for AWS IoT,
then you can pass in a transformWsUrl
function to the mqtt.connect()
options
This is needed because signed urls have an expiry and eventually upon reconnects, a new signed url needs to be created:
// This module doesn't actually exist, just an example
var awsIotUrlSigner = require('awsIotUrlSigner')
mqtt.connect('wss://a2ukbzaqo9vbpb.iot.ap-southeast-1.amazonaws.com/mqtt', {
transformWsUrl: function (url, options, client) {
// It's possible to inspect some state on options(pre parsed url components)
// and the client (reconnect state etc)
return awsIotUrlSigner(url)
}
})
// Now every time a new WebSocket connection is opened (hopefully not that
// often) we get a freshly signed url
Here is how QoS works:
About data consumption, obviously, QoS 2 > QoS 1 > QoS 0, if that's a concern to you.
This repo bundles TypeScript definition files for use in TypeScript projects and to support tools that can read .d.ts
files.
Before you can begin using these TypeScript definitions with your project, you need to make sure your project meets a few of these requirements:
{"compilerOptions" : {"moduleResolution" : "node"}, ...}
npm install --save-dev @types/node
MQTT.js is an OPEN Open Source Project. This means that:
Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project.
See the CONTRIBUTING.md file for more details.
MQTT.js is only possible due to the excellent work of the following contributors:
Adam Rudd | GitHub/adamvr | Twitter/@adam_vr |
---|---|---|
Matteo Collina | GitHub/mcollina | Twitter/@matteocollina |
Maxime Agor | GitHub/4rzael | Twitter/@4rzael |
MIT
FAQs
A library for the MQTT protocol
The npm package mqtt receives a total of 412,070 weekly downloads. As such, mqtt popularity was classified as popular.
We found that mqtt demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 7 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.